﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

namespace SimpleBlog.Mvc
{
    public class EmailAddressAttribute : RegularExpressionAttribute, IClientValidatable
    {
        private const string defaultErrorMessage = "'{0}' must be a valid email address";
        private Func<string> _errorMessageAccessor;

        public EmailAddressAttribute() :
            base("^[a-z0-9_\\+-]+(\\.[a-z0-9_\\+-]+)*@[a-z0-9]+(\\.[a-z0-9]+)*\\.([a-z]{2,4})$")
        {
        }

        public EmailAddressAttribute(Func<string> errorMessageAccessor)
            : this()
        {
            _errorMessageAccessor = errorMessageAccessor;
        }

        public override string FormatErrorMessage(string name)
        {
            if (_errorMessageAccessor == null)
                return string.Format(defaultErrorMessage, name);
            else
                return string.Format(_errorMessageAccessor(), name);
        }

        protected override ValidationResult IsValid(object value,
                                                ValidationContext validationContext)
        {
            if (value != null)
            {
                if (!base.IsValid(value))
                {
                    return new ValidationResult(
                        FormatErrorMessage(validationContext.DisplayName));
                }
            }

            return ValidationResult.Success;
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            yield return new ModelClientValidationRule()
            {
                ValidationType = "email",
                ErrorMessage = FormatErrorMessage(metadata.GetDisplayName())
            };
        }
    }
}